package ldh.im.fxgui.controller.sub;

import com.jfoenix.controls.JFXButton;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import ldh.im.dto.base.OkResp;
import ldh.im.dto.business.base.FeedbackCreateReq;
import ldh.im.fxbase.cell.ObjectTableCellFactory;
import ldh.im.fxbase.dao.ImFeedbackDao;
import ldh.im.fxbase.data.pojo.ImFeedback;
import ldh.im.fxbase.rpc.service.RpcBaseService;
import ldh.im.fxbase.util.*;
import ldh.im.fxgui.component.ImStage;
import ldh.im.fxgui.util.UiUtil;
import ldh.im.util.DateUtil;
import ldh.rpc.exception.RpcException;
import org.controlsfx.control.PopOver;
import org.controlsfx.validation.ValidationSupport;
import org.controlsfx.validation.Validator;

import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;

public class FeedbackController implements Initializable {

    private ImStage imStage;

    @FXML private StackPane root;
    @FXML private Pane feedbackListPane;
    @FXML private TableView<ImFeedback> feedbackTableView;
    @FXML private TableColumn<ImFeedback, Long> feedbackAction;
    @FXML private TableColumn<ImFeedback, Date> feedbackTime;
    @FXML private Pane editPane;
    @FXML private TextField titleTextField;
    @FXML private TextArea contentTextArea;

    private PopOver popOver = null;

    private ValidationSupport validationSupport = new ValidationSupport();

    public void setImStage(ImStage imStage) {
        this.imStage = imStage;
    }

    @FXML
    private void submitAct(ActionEvent actionEvent) {
        String title = titleTextField.getText().trim();
        String content = contentTextArea.getText();

        validationSupport.revalidate();
        if(validationSupport.isInvalid()) {
            return;
        }

//        if (StringUtil.isEmpty(title)) {
//            DialogUtil.alert(root, "错误", "标题不能为空");
//            return;
//        }
//        if (StringUtil.isEmpty(content)) {
//            DialogUtil.alert(root, "错误", "内容不能为空");
//            return;
//        }
        Task<ImFeedback> sendFeedback = new Task() {

            @Override
            protected Object call() throws Exception {
                RpcBaseService rpcBaseService = RpcUtil.getRpcBootstrap().getRpcConfig().getClientBean(RpcBaseService.class);
                FeedbackCreateReq feedbackCreateReq = new FeedbackCreateReq();
                feedbackCreateReq.setTitle(title);
                feedbackCreateReq.setContent(content);
                OkResp okResp = rpcBaseService.createFeedback(feedbackCreateReq);

                ImFeedbackDao feedbackDao = BeanFactory.getInstance().getBean(ImFeedbackDao.class);
                String userId = UiUtil.getLoginImUser().getUserId();
                ImFeedback feedback = new ImFeedback();
                feedback.setCurrentUserId(userId);
                feedback.setServerId(okResp.getOtherInfo());
                feedback.setTitle(title);
                feedback.setContent(content);
                feedbackDao.insert(feedback);

                return feedback;
            }
        };

        sendFeedback.setOnSucceeded(s->{
            showFeedbackListAct(null);
            titleTextField.setText("");
            contentTextArea.setText("");
        });
        sendFeedback.setOnFailed(e->{
            if(sendFeedback.getException() instanceof RpcException) {
                RpcException rpcException = (RpcException) sendFeedback.getException();
                String errMsg = rpcException.getMessage();
                DialogUtil.alert(imStage, "错误", errMsg);
            } else {
                DialogUtil.alert(imStage, "错误", "保存反馈信息失败");
            }
        });

        ThreadPoolUtil.submitTask(sendFeedback);
    }

    @FXML
    private void cancelAct(ActionEvent actionEvent) {
        imStage.close();
    }

    @FXML
    private void showFeedbackListAct(ActionEvent actionEvent) {
        editPane.setVisible(false);
        feedbackListPane.setVisible(true);
        loadData();
    }

    @FXML
    private void backAct(ActionEvent actionEvent) {
        editPane.setVisible(true);
        feedbackListPane.setVisible(false);
    }

    private void loadData() {
        Task<List<ImFeedback>> loadFeedbacks = new Task() {

            @Override
            protected Object call() throws Exception {
                ImFeedbackDao feedbackDao = BeanFactory.getInstance().getBean(ImFeedbackDao.class);
                String userId = UiUtil.getLoginImUser().getUserId();
                List<ImFeedback> feedbacks = feedbackDao.getAll(userId, 500);
                return feedbacks;
            }
        };

        loadFeedbacks.setOnSucceeded(s->{
            feedbackTableView.getItems().setAll(loadFeedbacks.getValue());
        });
        loadFeedbacks.setOnFailed(e->{
            if(loadFeedbacks.getException() instanceof RpcException) {
                RpcException rpcException = (RpcException) loadFeedbacks.getException();
                String errMsg = rpcException.getMessage();
                DialogUtil.alert(imStage, "错误", errMsg);
            } else {
                DialogUtil.alert(imStage, "错误", "加载反馈信息失败");
            }
        });

        ThreadPoolUtil.submitTask(loadFeedbacks, "加载反馈信息");
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        feedbackAction.setCellFactory(t->{
            return new TableCell<ImFeedback, Long>() {
                @Override
                protected void updateItem(Long item, boolean empty) {
                    super.updateItem(item, empty);

                    ImFeedback feedback = super.getTableRow().getItem();
                    if (empty || item == null) {
                        setText(null);
                        setGraphic(null);
                    } else {
                        setGraphic(createTableHandle(feedback));
                    }
                }
            };
        });

        feedbackTime.setCellFactory(new ObjectTableCellFactory<>(date->{
            return DateUtil.format(date, "yyyy-MM-dd");
        }));

        validationSupport.registerValidator(titleTextField, Validator.createEmptyValidator("标题不能为空"));
        validationSupport.registerValidator(contentTextArea, Validator.createEmptyValidator("内容不能为空"));
    }

    private ButtonBar createTableHandle(ImFeedback feedback) {
        ButtonBar buttonBar = new ButtonBar();
        JFXButton viewBtn = new JFXButton("查看反馈信息");
        viewBtn.setOnAction(e->{
            viewTable(viewBtn, feedback);
        });
        buttonBar.getButtons().addAll(viewBtn);
        return buttonBar;
    }

    private void viewTable(JFXButton viewBtn, ImFeedback feedback) {
        if (popOver == null) {
            popOver = buildPopOver();
        }
        popOver.setContentNode(createFeedbackInfoPane(feedback));
        double offset = -10;
        popOver.show(viewBtn, offset);
    }

    private PopOver buildPopOver() {
        PopOver popOver = new PopOver();
        popOver.setTitle("查看反馈信息");
        popOver.setMinWidth(200);
        popOver.setAnimated(true);
        popOver.setDetachable(false);

        popOver.setArrowLocation(PopOver.ArrowLocation.LEFT_CENTER);
        return popOver;
    }

    private Node createFeedbackInfoPane(ImFeedback feedback) {
        RegionUtil.FxmlBean<Node, FeedbackInfoController> fxmlBean = RegionUtil.loadFxmlBean(this.getClass().getResource("/fxml/sub/FeedbackInfoPane.fxml"));
        fxmlBean.getController().setFeedback(feedback);
        return fxmlBean.getNode();
    }


}
